package com.zbkj.front.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.together.TogetherJob;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.CommunityNoteFrontDiscoverRequest;
import com.zbkj.common.request.NovelListRequest;
import com.zbkj.common.request.PageParamRequest;
import com.zbkj.common.request.ProductFrontSearchRequest;
import com.zbkj.common.response.CommunityNoteFrontPageResponse;
import com.zbkj.common.response.NovelListResponse;
import com.zbkj.common.response.ProductFrontResponse;
import com.zbkj.common.result.CommonResult;
import com.zbkj.front.service.CommunityFrontService;
import com.zbkj.front.service.FrontProductService;
import com.zbkj.service.service.NovelService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author lzhCreate
 * @create 2024-07-02 16:38
 */
@Slf4j
@RestController
@RequestMapping("api/front/index/optimize")
@Api(tags = "首页瀑布流优化")
public class IndexWaterfallStreamOptimizeController {

    @Autowired
    private CommunityFrontService communityFrontService;

    @Autowired
    private TogetherController togetherController;

    @Autowired
    private FrontProductService productService;

    @Autowired
    private NovelService novelService;

    @ApiOperation(value = "合并首页瀑布流的接口")
    @GetMapping("/merge/api")
    public CommonResult<Map<String, Object>> getHomepageData(NovelListRequest listRequest,
                                                             @ModelAttribute @Validated ProductFrontSearchRequest productFrontSearchRequest,
                                                             @ModelAttribute @Validated CommunityNoteFrontDiscoverRequest request) {

        //保证不为null
        final CommunityNoteFrontDiscoverRequest finalRequest = (request == null) ? new CommunityNoteFrontDiscoverRequest() : request;
        final NovelListRequest finalListRequest = (listRequest == null) ? new NovelListRequest() : listRequest;
        final ProductFrontSearchRequest finalProductFrontSearchRequest = (request == null) ? new ProductFrontSearchRequest() : productFrontSearchRequest;

        // 这个接口用异步request会丢失
//        CompletableFuture<CommonPage<CommunityNoteFrontPageResponse>> communityData =
//                CompletableFuture.supplyAsync(() -> communityNoteController.findDiscoverNoteList(request));                                                             @ModelAttribute @Validated CommunityNoteFrontDiscoverRequest request) throws ExecutionException, InterruptedException {

        PageInfo<CommunityNoteFrontPageResponse> discoverNotePageInfo =
                communityFrontService.findDiscoverNoteList(finalRequest);

        // 启动异步请求
        CompletableFuture<PageInfo<TogetherJob>> togetherData =
                CompletableFuture.supplyAsync(() -> togetherController.myTaskHallList(finalRequest).getData());

        CompletableFuture<PageInfo<NovelListResponse>> novelData =
                CompletableFuture.supplyAsync(() -> novelService.index(finalListRequest));

        CompletableFuture<PageInfo<ProductFrontResponse>> productData =
                CompletableFuture.supplyAsync(() -> productService.getList(finalProductFrontSearchRequest, finalRequest));
        try {

            // 等待所有异步请求完成
//        CompletableFuture.allOf(communityData, togetherData, novelData, productData).join();
            CompletableFuture.allOf(togetherData, novelData, productData).join();
            // 合并结果
            PageInfo<TogetherJob> togetherJobPageInfo = togetherData.get();
            PageInfo<NovelListResponse> novelListResponsePageInfo = novelData.get();
            PageInfo<ProductFrontResponse> productFrontResponsePageInfo = productData.get();

            // 获取每个 PageInfo 对象中的 List
            List<CommunityNoteFrontPageResponse> discoverNoteList = discoverNotePageInfo.getList();
            List<TogetherJob> togetherJobList = togetherJobPageInfo.getList();
            List<NovelListResponse> novelList = novelListResponsePageInfo.getList();
            List<ProductFrontResponse> productList = productFrontResponsePageInfo.getList();

            // 定义权重
            int discoverNoteWeight = 6;
            int togetherJobWeight = 4;
            int productListWeight = 4;
            int novelListWeight = 4;

            // 存储结果的列表
            List<Object> sortedList = new ArrayList<>();

            // 初始化索引和计数器
            int discoverNoteIndex = 0, togetherJobIndex = 0, novelListIndex = 0, productListIndex = 0;

            // 按权重交叉排序
            while (discoverNoteIndex < discoverNoteList.size() || togetherJobIndex < togetherJobList.size() ||
                    novelListIndex < novelList.size() || productListIndex < productList.size()) {

                for (int i = 0; i < discoverNoteWeight && discoverNoteIndex < discoverNoteList.size(); i++) {
                    sortedList.add(discoverNoteList.get(discoverNoteIndex++));
                }

                for (int i = 0; i < togetherJobWeight && togetherJobIndex < togetherJobList.size(); i++) {
                    sortedList.add(togetherJobList.get(togetherJobIndex++));
                }

                for (int i = 0; i < productListWeight && productListIndex < productList.size(); i++) {
                    sortedList.add(productList.get(productListIndex++));
                }

                for (int i = 0; i < novelListWeight && novelListIndex < novelList.size(); i++) {
                    sortedList.add(novelList.get(novelListIndex++));
                }
            }

            Map<String, Object> response = new HashMap<>();
            Page<List<Object>> responsePage = PageHelper.startPage(listRequest.getPage(), listRequest.getLimit());
            response.put("sortedList", CommonPage.copyPageInfo(responsePage, sortedList));
            return CommonResult.success(response);

//            response.put("discoverNote", discoverNotePageInfo);
//            response.put("together", togetherJobPageInfo);
//            response.put("novel", novelListResponsePageInfo);
//            response.put("product", productFrontResponsePageInfo);
//            return CommonResult.success(response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CrmebException("首页瀑布流出现异常:" + e.getMessage());
        }
    }
}
